<script lang="ts" setup>
  import { ref, computed, watch, reactive } from 'vue';
  import { Modal, Message, Space } from '@arco-design/web-vue';
  import type { ArticleColumnRecord } from '/@/api/model/recommendModel';
  import { deleteSpColumn } from '/@/api/column';
  import type { SpColumnRecord } from '/@/api/model/columnModel';
  import { useRouter } from 'vue-router';
  import { PageEnum } from '/@/enums/pageEnum';
  import { isEmpty } from 'lodash-es';
  import { queryArticleColumnList } from '/@/api/recommend';
  import { ApiManageList } from '/@/components/ApiManageList';
import type { CollectionsRecord } from '/@/api/model/creatorModel';
import { addCollections, queryCollectionsPage } from '/@/api/web/creator';

  const router = useRouter();
  const apiManageList = ref();
  const isUpdate = ref(false);
  const modelVisible = ref(false);
  const formRef = ref();
  type FormRecord = Pick<CollectionsRecord, 'name' | 'desc' | 'state' >;
  const form = reactive<FormRecord>({
    name: '',
    desc: '',
    state: 0,
  });
  const options = [
    {
      label: '公开',
      value: 0,
    },
    {
      label: '隐私',
      value: 1,
    },
  ];

  const statusTabs = computed(() => {
    return [{key: 'all', api: queryCollectionsPage }];
  });
  const toAdd = () => {
    formRef.value.resetFields();
    isUpdate.value = false;
    modelVisible.value = true;
  };
  const toEdit = ({ item }: { item: CollectionsRecord }) => {
    formRef.value.resetFields();
    isUpdate.value = true;
    Object.assign(form, item);
    modelVisible.value = true;
  };
  const onDelete = ({ item, reload }: { item: CollectionsRecord; reload: PromiseFn }) => {
    Modal.warning({
      title: '删除收藏集',
      content: '删除收藏后收藏的文章也会被删除，确定删除吗？',
      onOk: async () => {
        try {
          await deleteSpColumn(item.id);
          Message.success('删除成功');
          reload();
        } catch (err) {
          Message.error((err as Error).message || '删除失败');
        }
      },
    });
  };
  // const toEditContent = ({ item }: { item: SpColumnRecord }) => {
  //   router.push(`/creator/content/sp_column/edit/${item.id}`);
  // };
  const callActions = (): Array<{ label: string, onClick: ({ item }: { item: CollectionsRecord }) => void }> => {
  const actions = [
    { label: '修改', onClick: toEdit },
    { label: '删除', onClick: onDelete },
  ];
  return actions;
};

  const getSpColumnEditModalTitle = computed(() => {
    return isUpdate.value ? '修改收藏集' : '新建收藏集';
  });
  const reload = () => {
    apiManageList.value?.forEach((item) => item.reload());
  };
  const onSubmit = async () => {
    const errors = await formRef.value.validate?.();
    if (!isEmpty(errors)) {
      return false;
    }
    const result = await addCollections({
      name: form.name,
      desc: form.desc,
      state: form.state
    });
    if (result.id) {
      reload();
    }
  };
  const articleColumnListRef = ref<ArticleColumnRecord[]>([]);

  (async () => {
    const data = await queryArticleColumnList();
    articleColumnListRef.value = data;
  })();

  // 标签页
  const activeKey = ref('');
  watch(
    router.currentRoute,
    ({ path }) => {
      activeKey.value = path;
    },
    { immediate: true },
  );
  watch(activeKey, (key) => {
    if (key !== router.currentRoute.value.path) {
      router.push(key);
    }
  });

  // 文章状态
  const statusKey = ref('');
  const queryStatus = computed(() => {
    const { status } = router.currentRoute.value.query;
    return Array.isArray(status) ? status[0] : status;
  });
  watch(
    router.currentRoute,
    () => {
      if (router.currentRoute.value.path !== PageEnum.CREATOR_RESOURCES_FAVORITE) return;
      if (queryStatus.value && ['all', 'published', 'rejected'].includes(queryStatus.value)) {
        statusKey.value = queryStatus.value;
      } else {
        router.push({ query: { status: 'all' } });
      }
    },
    { immediate: true },
  );
  watch(statusKey, (status) => {
    if (router.currentRoute.value.path !== PageEnum.CREATOR_CONTENT_SP_COLUMN) return;
    if (status !== queryStatus.value) {
      router.push({ query: { status } });
    }
  });

 
</script>
<template>
  <div>
    <a-card :bordered="false">
      <a-tabs class="mb-[14px]" hoverable v-model:activeKey="activeKey" lazyLoad destroyOnHide>
        <a-tabPane title="收藏集" :key="PageEnum.CREATOR_RESOURCES_FAVORITE">
          <!-- <a-tabs lazyLoad v-model:activeKey="statusKey" type="text" destroyOnHide>
            <a-tabPane > -->
              <template  v-for="item in statusTabs" :key="item.key" >
              <ApiManageList
                ref="apiManageList"
                :api="item.api"
                :params="{ status: item.key }"
                :getLink="(item) => `/sp_column/${item.id}`"
                :actions="callActions"
                :fieldNames="{
                  title: 'name',
                }"
              >
                <template #desc="{ data }: { data: SpColumnRecord }">
                  <Space :size="[24, 0]" class="text-gray-500">
                    <template #split>|</template>
                    <span>{{ data.updateTime }}</span>
                    <Space :size="[12, 0]">
                      <template #split>·</template>
                      <span>文章数{{ data.article_num }}</span>
                      <span>订阅人数{{ data.subscribe_num }}</span>
                    </Space>
                  </Space>
                </template>
              </ApiManageList>
            </template>
            <!-- </a-tabPane>
          </a-tabs> -->
        </a-tabPane>
      </a-tabs>
      <a-button class="absolute right-[30px] top-[12px]" type="primary" @click="toAdd"
        >新建收藏集</a-button
      >

      <a-modal
        v-model:visible="modelVisible"
        :title="getSpColumnEditModalTitle"
        :on-before-ok="onSubmit"
      >
        <a-form :model="form" ref="formRef">
          <a-form-item field="name" label="名称" label-col-flex="80px" required>
            <a-input v-model="form.name" :maxLength="50" showWordLimit />
          </a-form-item>
          <a-form-item field="desc" label="描述" label-col-flex="80px">
            <a-textarea v-model="form.desc" :maxLength="150" showWordLimit />
          </a-form-item>
          <a-form-item label="状态" label-col-flex="80px">
            <a-radio-group v-model="form.state" :options="options"> </a-radio-group>
          </a-form-item>
        </a-form>
      </a-modal>
    </a-card>
  </div>
</template>

